/*
 * AppLogger.cpp
 */

#include "AppLogger.h"
#include "log.h"

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

// initialize this to false
bool AppLogger::logInited = false;

const char * LOG_FILE_NAME = "nwprog.log";

// the output buffer that we'll use in case of variable argument list type of logging
static char printBuffer[64 * 1024];

void printToBuffer(char * format, ...)
{
	va_list args;
	va_start (args, format);
	vsprintf (printBuffer,format, args);
	va_end (args);
}

AppLogger * AppLogger::getInstance(const char* moduleName) {
	AppLogger::initLogSettings();

	AppLogger * appLogger = new AppLogger(moduleName);

	return appLogger;
}

AppLogger::AppLogger(const char* moduleName) {
	if (NULL == moduleName) {
		fprintf(stderr, "AppLogger must be initialized with an moduleName!");
		exit(-1);
	}

	this->moduleName = moduleName;

}

AppLogger::~AppLogger() {

}

void AppLogger::initLogSettings() {
	if (!logInited) {
		logInited = true;
		FILE* pFile = fopen(LOG_FILE_NAME, "a");
		Output2FILE::Stream() = pFile;
		FILELog::ReportingLevel() = logDEBUG;
	}
}

//output message as debug level
void AppLogger::debug(const char * msg) {
	FILE_LOG(logDEBUG)
		<< " | " << getpid() << "-" << (unsigned int) pthread_self() << " | "
				<< this->moduleName << " | " << msg;
}

//log messages with format and variable argument list
void AppLogger::debug(string format, ...) {
	va_list args;
	va_start (args, format);
	vsprintf (printBuffer,format.c_str(), args);
	va_end (args);

	FILE_LOG(logDEBUG)
	<< " | " << getpid() << "-" << (unsigned int)pthread_self() << " | "
	<< this->moduleName << " | " << printBuffer;
}

//output message as info level
void AppLogger::info(const char* msg) {
	FILE_LOG(logINFO)
		<< " | " << getpid() << "-" << (unsigned int) pthread_self() << " | "
				<< this->moduleName << " | " << msg;
}

//log messages with format and variable argument list, at info level
void AppLogger::info(string format, ...) {
	va_list args;
	va_start (args, format);
	vsprintf (printBuffer,format.c_str(), args);
	va_end (args);

	FILE_LOG(logINFO)
	<< " | " << getpid() << "-" << (unsigned int)pthread_self() << " | "
	<< this->moduleName << " | " << printBuffer;
}

//output message as error level
void AppLogger::error(const char* msg) {
	FILE_LOG(logERROR)
		<< " | " << getpid() << "-" << (unsigned int) pthread_self() << " | "
				<< this->moduleName << " | " << msg;

}

//log messages with format and variable argument list, at error level
void AppLogger::error(string format, ...) {
	va_list args;
	va_start (args, format);
	vsprintf (printBuffer,format.c_str(), args);
	va_end (args);

	FILE_LOG(logERROR)
	<< " | " << getpid() << "-" << (unsigned int)pthread_self() << " | "
	<< this->moduleName << " | " << printBuffer;
}
